package com.swufe.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridLayout;

import java.util.ArrayList;
import java.util.List;
/*2022/5/29
卡片的移动，游戏的初始化
* 算法思想参考开源代码,网址：
https://blog.csdn.net/weixin_30139213/article/details/117645551?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2-117645551-blog-111472349.pc_relevant_downloadblacklistv1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2-117645551-blog-111472349.pc_relevant_downloadblacklistv1&utm_relevant_index=4
*/
public class GameView extends GridLayout {
    private static final String TAG = "GameView";
    public static GameView gameView;
    private float startX, startY, offsetX, offsetY;//记录起始位置和偏移坐标
    private Card[][] cardsMap = new Card[4][4];//添加卡片的方法
    private List<Point> emptyPoint = new ArrayList<Point>();//添加随机数
    public GameView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        gameView = this;
        initGameView();
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        gameView = this;
        initGameView();
    }

    public GameView(Context context) {
        super(context);
        gameView = this;
        initGameView();
    }
    private int GetCardWidth() {
        //屏幕信息的对象
        DisplayMetrics displayMetrics;
        displayMetrics = getResources().getDisplayMetrics();

        //获取屏幕信息
        int cardWidth;
        cardWidth = displayMetrics.widthPixels;

        return (cardWidth - 10) / 4;//-10是用来间隔每个卡片的距离
    }
    //游戏初始化方法
    private void initGameView() {
        //将面板设置成4列
        setColumnCount(4);
        setBackgroundColor(0xffbbada0);
        addCards(GetCardWidth(), GetCardWidth());
        Log.i(TAG, "initGameView: ");
        setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();//startX:手机刚开始在屏幕上的X坐标
                        startY = event.getY();//startY:手机刚开始在屏幕上的Y坐标
                        break;
                    case MotionEvent.ACTION_UP:
                        offsetX = event.getX() - startX;
                        offsetY = event.getY() - startY;//offsetX,offsetY,分别是手指在屏幕上的X,Y上的偏移量

                        if (Math.abs(offsetX) > Math.abs(offsetY)) {
                            if (offsetX <-5) {//手势往左，-5表示范围
                                swipeLeft();
                                Log.i(TAG, "onTouch: Left");

                            } else if (offsetX > 5) {
                                swipeRight();
                                Log.i(TAG, "onTouch: Right");
                            }

                        } else {
                            if (offsetY <-5) {
                                swipeUp();
                                Log.i(TAG, "onTouch: up");
                            } else if (offsetY > 5) {
                                swipeDown();
                                Log.i(TAG, "onTouch: Down");
                            }
                        }
                        break;
                }
                return true;
            }
        });
    }
    private void addCards(int cardWith, int cardHeight) {
        Card c;
        //遍历每一张卡片
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                c = new Card(getContext());
                c.setNum(2);//给每一张卡片赋值
                addView(c, cardWith, cardHeight);
                cardsMap[x][y] = c;
            }
        }
    }

    //开始游戏的方法
    public void startGame() {
        MainActivity.getMainActivity().clearScore();
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                cardsMap[x][y].setNum(0);
                emptyPoint.add(new Point(x, y));
            }
        }
        addRandomNum();
    }
    private void addRandomNum() {
        emptyPoint.clear();
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                if (cardsMap[x][y].getNum() <= 0) {
                    emptyPoint.add(new Point(x, y));
                }
            }
        }
        Point p = emptyPoint.remove((int) (Math.random() * emptyPoint.size()));
        cardsMap[p.x][p.y].setNum(Math.random() > 0.1 ? 2 : 4);
        Log.i("addRandomNum: ",cardsMap[p.x][p.y].getNum()+"");
    }

    //向左滑动
    public void swipeLeft() {
        boolean meger = false;//判断是否需要添加数字
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                for (int x1 = x + 1; x1 < 4; x1++) {
                    if (cardsMap[x1][y].getNum() > 0) {
                        if (cardsMap[x][y].getNum() <= 0) {
                            cardsMap[x][y].setNum(
                                    cardsMap[x1][y].getNum());
                            cardsMap[x1][y].setNum(0);
                            x--;
                            meger = true;
                            break;
                        } else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x1][y].setNum(0);
                            MainActivity.getMainActivity().
                                    addScore(cardsMap[x][y].getNum());
                            meger = true;
                        }
                        break;
                    }
                }
            }
        }
        if (meger) {
            addRandomNum();
            checkComplete();
        }
    }

    //向右滑动
    public void swipeRight() {
        boolean meger = false;
        for (int y = 0; y < 4; y++) {
            for (int x = 3; x >= 0; x--) {
                for (int x1 = x - 1; x1 >= 0; x1--) {
                    if (cardsMap[x1][y].getNum() > 0) {
                        if (cardsMap[x][y].getNum() <= 0) {
                            cardsMap[x][y].setNum(
                                    cardsMap[x1][y].getNum());
                            cardsMap[x1][y].setNum(0);
                            x++;
                            meger = true;
                            break;
                        } else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x1][y].setNum(0);
                            MainActivity.getMainActivity().
                                    addScore(cardsMap[x][y].getNum());
                            meger = true;
                        }
                        break;
                    }
                }
            }
        }
        if (meger) {
            addRandomNum();
            checkComplete();
        }
    }

    //向上滑动
    public void swipeUp() {
        boolean meger = false;
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                for (int y1 = y + 1; y1 < 4; y1++) {
                    if (cardsMap[x][y1].getNum() > 0) {
                        if (cardsMap[x][y].getNum() <= 0) {
                            cardsMap[x][y].setNum(
                                    cardsMap[x][y1].getNum());
                            cardsMap[x][y1].setNum(0);
                            y--;
                            meger = true;
                            break;
                        } else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x][y1].setNum(0);
                            MainActivity.getMainActivity().
                                    addScore(cardsMap[x][y].getNum());
                            meger = true;
                        }
                        break;
                    }
                }
            }
        }
        if (meger) {
            addRandomNum();
            checkComplete();
        }
    }

    //向下滑动
    public void swipeDown() {
        boolean meger = false;
        for (int x = 0; x < 4; x++) {
            for (int y = 3; y >= 0; y--) {
                for (int y1 = y - 1; y1 >= 0; y1--) {
                    if (cardsMap[x][y1].getNum() > 0) {
                        if (cardsMap[x][y].getNum() <= 0) {
                            cardsMap[x][y].setNum(
                                    cardsMap[x][y1].getNum());
                            cardsMap[x][y1].setNum(0);
                            y++;
                            meger = true;
                            break;
                        } else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x][y1].setNum(0);
                            MainActivity.getMainActivity().
                                    addScore(cardsMap[x][y].getNum());
                            meger = true;
                        }
                        break;
                    }
                }
            }
        }
        if (meger) {
            addRandomNum();
            checkComplete();
        }
    }
        //检查游戏是否结束的方法
        public void checkComplete () {
            boolean complete = true;//记录游戏的状态
            ALL:
            for (int y = 0; y < 4; y++) {
                for (int x = 0; x < 4; x++) {
                    if (cardsMap[x][y].getNum() == 0 ||
                            (x > 0 && cardsMap[x][y].equals(cardsMap[x - 1][y])) ||
                            (x < 3 && cardsMap[x][y].equals(cardsMap[x + 1][y])) ||
                            (y > 0 && cardsMap[x][y].equals(cardsMap[x][y - 1])) ||
                            (y < 3 && cardsMap[x][y].equals(cardsMap[x][y + 1]))) {
                        complete = false;
                        break ALL;
                        //break 用于跳出循环，但是只能跳出一层循环
                        //break ALL:可跳出所有的循环
                    }
                }
            }
            if (complete) {
                new AlertDialog.Builder(getContext())
                        .setTitle("很遗憾")
                        .setMessage("游戏已结束")
                        .setPositiveButton("重来", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                startGame();
                            }
                        })
                        .setNegativeButton("退出", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                                int which) {
                                MainActivity.getMainActivity().finish();
                            }
                        }).show();
            }
        }
    //当布局的尺寸发生变化时，会执行该方法
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        startGame();
    }
    }

